<template>
  <view class="container" :style="appThemeStyle">
    <z-paging ref="paging" v-model="list" class="notice-list" @query="getlist">
      <view class="content-wrapper">
        <view class="order-list">
          <view class="order-item" v-for="(item, index) in list" :key="index" @click="toDetail(item)">
            <view class="item-header">
              <view class="date-section">
                <text class="date">{{ item.date }}</text>
                <text class="record-date">{{ item.recordDate ? item.recordDate.split(' ')[0] : '' }}</text>
                <image
                  class="checkbox-image"
                  :src="selectedItems.includes(item) ? '../../static/xz.png' : '../../static/mx.png'"
                  @tap.stop="selectItem(item)"
                />
              </view>
              <view class="metrics-grid">
                <view class="metric-card">
                  <view class="metric-label">体重</view>
                  <view class="metric-value">
                    <text class="number">{{ item.fitness.weight.value }}</text>
                    <text class="unit">kg</text>
                  </view>
                </view>
                <view class="metric-card">
                  <view class="metric-label">体脂</view>
                  <view class="metric-value">
                    <text class="number">{{ item.fitness.fat.value }}</text>
                    <text class="unit">%</text>
                  </view>
                </view>
                <view class="metric-card">
                  <view class="metric-label">腰围</view>
                  <view class="metric-value">
                    <text class="number">{{ item.fitness.waist.value }}</text>
                    <text class="unit">cm</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <template #bottom>
        <view class="bottom-button-wrapper">
          <view class="f ac xb " style="padding: 0 20rpx">
            <view class="tc add mr20r" style="width: 33%" @click="addData">
              添加数据
            </view>
            <view
              class="tc choose mr20r"
              style="width: 33%"
              :class="{ disabled: selectedItems.length !== 2 }"
              @click="generateChart"
            >
              {{ showChart ? "隐藏对比图" : "生成对比图" }}
            </view>
          </view>
          <view class="f ac xb " style="padding: 20rpx">
            <view
              class="tc delete"
              style="width: 100%"
              :class="{ disabled: selectedItems.length === 0 }"
              @click="confirmDelete"
            >
              一键删除
            </view>
          </view>
        </view>
      </template>
    </z-paging>

    <!-- 弹窗 -->
    <view v-if="showChart" class="modal" @click="closeModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <view class="chart-title">数据对比</view>
          <view class="close-btn" @click="closeModal">×</view>
        </view>
        <view class="training-stats">
          <view class="stat-item">
            <text class="stat-label">总训练次数</text>
            <view class="stat-value-wrapper">
              <input 
                type="number" 
                v-model="totalCount"
                class="stat-input"
                @blur="updateTotalCount"
              />
              <text class="stat-unit">次</text>
            </view>
          </view>
          <view class="stat-item">
            <text class="stat-label">本周训练</text>
            <view class="stat-value-wrapper">
              <text class="stat-prefix">第</text>
              <input 
                type="number" 
                v-model="weekTrainingCount"
                class="stat-input"
                @blur="updateWeekCount"
              />
              <text class="stat-unit">次</text>
            </view>
          </view>
        </view>
        <view class="charts">
          <qiun-data-charts
            type="line"
            :opts="opts"
            :chartData="chartData"
            :canvas2d="true"
            canvasId="compareChart"
          />
        </view>
        <u-button  color="#000" text="分享计划" shape="circle" open-type="share"></u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { fitness, deleteFitness, planIns } from "../../api/fit";
export default {
  data() {
    return {
      keyword: "",
      list: [],
      selectedItems: [], // 存储选中的项目
      showChart: false, // 控制图表显示/隐藏
      id: "",
      totalCount: 0, // 训练总次数
      opts: {
        color: ["#1890FF", "#91CB74", "#FAC858"],
        padding: [15, 15, 15, 15],
        enableScroll: false,
        legend: {
          show: true,
          position: "top",
          float: "center",
        },
        xAxis: {
          type: "category",
          boundaryGap: true,
        },
        yAxis: {
          splitLine: true,
          axisLine: true,
          scale: true,
          min: 0,
          max: 100,
          interval: 10,
        },
        extra: {
          line: {
            type: "straight",
            width: 2,
            activeType: "hollow",
          },
        },
      },
      chartData: {
        categories: [],
        series: [],
      },
      weekTrainingCount: 0,
    };
  },
  onLoad(e) {
    console.log(e, "eeeeeeeeeeee");
    this.id = e.id;
    if (e.sharedChartData) {
      this.showChart = true;
      this.chartData = JSON.parse(decodeURIComponent(e.sharedChartData));
    }
  },

  onShareAppMessage(res) {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title:  "健康数据",
      path: `/pages/physical/index?id=${this.id}`,
    };
  },
  methods: {
    // 选择项目
    selectItem(item) {
      const index = this.selectedItems.indexOf(item);
      if (index > -1) {
        // 取消选择
        this.selectedItems.splice(index, 1);
        // 如果取消选择后不足两项，隐藏图表
        if (this.selectedItems.length < 2) {
          this.showChart = false;
        }
      } else if (this.selectedItems.length < 2) {
        // 添加选择
        this.selectedItems.push(item);
      }
    },

    // 判断是否禁用选择框
    isCheckboxDisabled(item) {
      return (
        this.selectedItems.length >= 2 && !this.selectedItems.includes(item)
      );
    },
    toDetail(val){
      uni.navigateTo({
        url: `/pages/physical/detail?id=${this.id}&customerId=${val.id}`,
      });
    },
    onShow() {
    this.$refs.paging.reload();
  },

    // 修改获取本周的开始和结束时间方法
    getWeekDates() {
      const now = new Date();
      const currentDay = now.getDay() || 7;
      const monday = new Date(now);
      monday.setDate(now.getDate() - (currentDay - 1));
      const sunday = new Date(now);
      sunday.setDate(now.getDate() + (7 - currentDay));
      // 修改格式化日期方法，使用标准格式
      const formatDateTime = (date, isEndTime = false) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const time = isEndTime ? '23:59:59' : '00:00:00';
        
        // 使用标准的日期时间格式
        return `${year}-${month}-${day} ${time}`;
      };
      
      return {
        startTime: formatDateTime(monday),
        endTime: formatDateTime(sunday, true)
      };
    },

    // 获取本周训练次数
    async getWeekTrainingCount() {
      try {
        const { startTime, endTime } = this.getWeekDates();
        const res = await planIns({
          startTime,
          endTime,
          customerId: this.id
        });
        
        if (res.code === 200) {
          this.weekTrainingCount = res.data.total || 0;
        }
      } catch (error) {
        console.error('获取训练次数错误:', error);
      }
    },

    // 修改生成对比图方法
    async generateChart() {
      if (this.selectedItems.length !== 2) {
        return;
      }
      
      // 获取本周训练次数
      await this.getWeekTrainingCount();
      
      // 获取总训练次数
      await this.getTotalCount();
      
      // 修改图表生成逻辑，使用 recordDate
      const dates = this.selectedItems.map(item => {
        // 如果有 recordDate，只显示日期部分
        return item.recordDate ? item.recordDate.split(' ')[0] : '';
      });
      const weights = this.selectedItems.map(item => item.fitness.weight.value);
      const fats = this.selectedItems.map(item => item.fitness.fat.value);
      const waists = this.selectedItems.map(item => item.fitness.waist.value);

      this.chartData = {
        categories: dates,
        series: [
          {
            name: "体重",
            data: weights
          },
          {
            name: "体脂",
            data: fats
          },
          {
            name: "腰围",
            data: waists
          }
        ]
      };
      
      this.showChart = true;
    },

    // 获取总训练次数
    async getTotalCount() {
      try {
        const res = await planIns({});
        if (res.code === 200) {
          this.totalCount = res.data.total || 0;
        } else {
          console.error('获取总训练次数失败:', res.message);
        }
      } catch (error) {
        console.error('获取总训练次数错误:', error);
      }
    },

    async getlist(pageNo, pageNum = 10) {
      // 模拟数据，实际项目中替换为真实的API调用
      let data = {
        page: pageNo,
        size: pageNum,
        recordDate: "",
        customerId:this.id
      };
      const res = await fitness(data);
      console.log(res,'12312312')
      this.$refs.paging.complete(res.data.list);
    },

    addData() {
      uni.navigateTo({
        url: `/pages/physical/data?id=${this.id}`,
      });
    },

    // 确认删除选中的数据
    confirmDelete() {
      if (this.selectedItems.length === 0) {
        uni.showToast({
          title: "请选择要删除的数据",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "确认删除",
        content: "是否删除已选择的数据？",
        success: (res) => {
          if (res.confirm) {
            this.deleteSelectedItems();
          }
        },
      });
    },

    // 删除选中的数据
    async deleteSelectedItems() {
      const ids = this.selectedItems.map((item) => item.id);
      try {
        await deleteFitness(ids);
        uni.showToast({
          title: "删除成功",
          icon: "success",
        });
        this.selectedItems = [];
        this.getlist(1); // 重新获取列表数据
      } catch (error) {
        uni.showToast({
          title: "删除失败",
          icon: "none",
        });
      }
    },

    // 修改分享图表方法
    shareChart() {
      // 构建要分享的数据
      const shareData = {
        chartData: this.chartData,
        totalCount: this.totalCount,
        weekTrainingCount: this.weekTrainingCount
      };
      
      // 显示分享菜单
      // uni.showShareMenu({
      //   withShareTicket: true,
      //   menus: ['shareAppMessage', 'shareTimeline']
      // });
      
      // 显示分享提示
      uni.showToast({
        title: '请点击右上角分享',
        icon: 'none',
        duration: 2000
      });
    },

    // 更新总训练次数
    updateTotalCount() {
      // 这里可以添加数据验证
      if (this.totalCount < 0) {
        this.totalCount = 0;
      }
      // 可以在这里调用接口更新数据
    },
    
    // 更新本周训练次数
    updateWeekCount() {
      // 这里可以添加数据验证
      if (this.weekTrainingCount < 0) {
        this.weekTrainingCount = 0;
      }
      // 可以在这里调用接口更新数据
    },

    // 添加关闭弹窗方法
    closeModal() {
      this.showChart = false;
      // 清空选中状态
      this.selectedItems = [];
    },

    // 添加分享给朋友的方法
    onShareAppMessage() {
      // 构建分享数据
      const shareData = {
        chartData: this.chartData,
        totalCount: this.totalCount,
        weekTrainingCount: this.weekTrainingCount
      };

      return {
        title: '体测数据对比',
        path: `/pages/physical/duibi?shareData=${encodeURIComponent(JSON.stringify(shareData))}`,
        imageUrl: '../../static/logo.jpg',
      }
    },

    // 添加分享到朋友圈的方法
    onShareTimeline() {
      const shareData = {
        chartData: this.chartData,
        totalCount: this.totalCount,
        weekTrainingCount: this.weekTrainingCount
      };

      return {
        title: '体测数据对比',
        query: `shareData=${encodeURIComponent(JSON.stringify(shareData))}`,
        imageUrl: '../../static/logo.jpg'
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.order-item {
  margin: 30rpx auto;
  padding: 30rpx;
  width: 92%;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1), 0 1rpx 8rpx rgba(0, 0, 0, 0.06);
  transform: translateY(0);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-6rpx);
    box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.12),
      0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  }
}

.date-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  margin-bottom: 30rpx;

  .date {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }

  .record-date {
    font-size: 28rpx;
    color: #999;
  }

  .checkbox-image {
    width: 40rpx;
    height: 40rpx;
  }
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  padding: 10rpx 0;
}

.metric-card {
  background: linear-gradient(145deg, #ffffff, #f5f5f5);
  padding: 20rpx;
  border-radius: 16rpx;
  text-align: center;
  box-shadow: 8rpx 8rpx 16rpx #e6e6e6, -8rpx -8rpx 16rpx #ffffff;

  .metric-label {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
  }

  .metric-value {
    display: flex;
    justify-content: center;
    align-items: baseline;

    .number {
      font-size: 40rpx;
      font-weight: 600;
      color: #000;
      line-height: 1;
    }

    .unit {
      font-size: 24rpx;
      color: #999;
      margin-left: 4rpx;
    }
  }
}

.content-wrapper {
  padding-bottom: 120rpx; // 为底部按钮留出空间
}

.bottom-button-wrapper {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f5f5f5;
  z-index: 100;
  padding-bottom: env(safe-area-inset-bottom); // 适配全面屏
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200;
}

.modal-content {
  background: #fff;
  padding: 30rpx;
  border-radius: 20rpx;
  width: 90%;
  max-width: 600rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
  position: relative; // 添加相对定位
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  .close-btn {
    font-size: 40rpx;
    color: #999;
    padding: 10rpx;
    cursor: pointer;
    
    &:active {
      opacity: 0.7;
    }
  }
}

.chart-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 30rpx;
  letter-spacing: 1rpx;
}

.training-stats {
  display: flex;
  justify-content: space-around;
  margin: 20rpx 0 30rpx;
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
  
  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
    
    .stat-label {
      font-size: 26rpx;
      color: #666;
    }
    
    .stat-value-wrapper {
      display: flex;
      align-items: center;
      gap: 4rpx;
      
      .stat-prefix {
        font-size: 28rpx;
        color: #333;
      }
      
      .stat-input {
        width: 80rpx;
        height: 60rpx;
        text-align: center;
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        background: #fff;
        border: 2rpx solid #ddd;
        border-radius: 8rpx;
        padding: 0 10rpx;
        
        &:focus {
          border-color: #000;
          outline: none;
        }
      }
      
      .stat-unit {
        font-size: 28rpx;
        color: #666;
      }
    }
  }
}

.charts {
  width: 100%;
  height: 600rpx;
}

// 修改底部按钮样式，确保在固定位置显示正常
.add,
.choose,
.delete {
  padding: 30rpx;
  background: #000;
  color: #fff;
  border-radius: 16rpx;
  font-weight: 500;
  letter-spacing: 2rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  position: relative; // 确保按钮显示在最上层
  z-index: 101;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
  }

  &.disabled {
    background: #999;
    box-shadow: none;
  }
}

// 修改checkbox样式
::v-deep .uni-checkbox-input {
  border-radius: 50%;
  border-color: #000;

  &.uni-checkbox-input-checked {
    background-color: #000;
    border-color: #000;
  }

  &.uni-checkbox-input-checked::after {
    color: #000 !important; // 选中对号改为黑色，使用 !important 确保覆盖
  }
}

// 选中状态的卡片样式
.order-item.selected {
  border: 2rpx solid #000;
  background: linear-gradient(145deg, #ffffff, #fafafa);
}
</style>
